<?php

namespace App\Http\Controllers\Api;

use App\SetTopRecord;
use App\SetTopRule;
use App\UserFollow;
use EasyWeChat\Support\File;
use Illuminate\Http\Request;
use App\Http\Services\UserManager;
use App\Http\Services\FileManager;
use App\User;
use App\Userinfo;
use App\Position;
use App\PositionImg;
use App\PersonalAuth;
use App\CompanyInfo;
use App\Trade;
use App\JobType;
use App\Http\Requests;
use DB;
use App\Http\Controllers\Controller;

class PositionController extends Controller
{
    public function getIndustryList(Request $request){
        /** @var Trade $trade */
        $trade = Trade::orderBy('sort','asc')->orderBy('created_at','desc')->get();
        if(count($trade) > 0){
            foreach($trade as $trad) {
                $jobType = JobType::whereTradeId($trad->id)->get();
                $job = array();
                if (count($jobType) > 0) {
                    foreach ($jobType as $jobT) {
                        array_push($job,$jobT);
                    }
                }

                $trad->job = $job;
            }
        }
        return response()->json(['level' => 'success','message' => '获取成功','data' => $trade]);
    }

    public function getPositionType(Request $request){
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录','data' => 'no_login']);

//        $companyInfo = CompanyInfo::whereUserId($user->id)->first();
//        if(!$companyInfo)
//            return response()->json(['level' => 'error','message' => '请进行企业认证']);

        $jobType = JobType::wherePid(0)->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $jobType]);
    }

    public function createPositionInfo(Request $request){
        $type            = $request->get('type');
        $jobTypeId       = $request->get('job_type_id');
        $peopleNum       = $request->get('people_num');
        $startTime       = $request->get('start_time');
        $endTime         = $request->get('end_time');
        $salaryType      = $request->get('salary_type');
        $salaryNum       = $request->get('salary_num');
        $contactName     = $request->get('contact_name');
        $contactPhone    = $request->get('contact_phone');
        $province        = $request->get('province');
        $sex             = $request->get('sex');
        $city            = $request->get('city');
        $area            = $request->get('area');
        $town           =$request->get('town');
        $addressDetail   = $request->get('address_detail');
        $desc            = $request->get('desc');
        $positionImgs    = $request->get('position_imgs');
        $education       = $request->get('education');
        $id              = !is_null($request->get('id'))?$request->get('id'):0;


        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录','data' => 'no_login']);

        $newPosition = Position::whereUserId($user->id)->whereId($id)->first();
        if(!$newPosition)
            $newPosition = new Position();

        $newPosition->user_id = $user->id;
        if(!is_null($type))$newPosition->type = $type;
        if(!is_null($jobTypeId)){
            /** @var JobType $thatJobType */
            $thatJobType = JobType::whereId($jobTypeId)->first();
            if(!$thatJobType)
                return response()->json(['level' => 'error','message' => '所选职位不存在']);

            $newPosition->job_type_id = $jobTypeId;
            $newPosition->trade_id    = $thatJobType->trade_id;
        }
        if(!is_null($peopleNum))$newPosition->people_num = $peopleNum;
        if(!is_null($startTime))$newPosition->start_time = $startTime;
        if(!is_null($endTime))$newPosition->end_time = $endTime;
        if(!is_null($salaryType))$newPosition->salary_type = $salaryType;
        if(!is_null($salaryNum))$newPosition->salary_num = $salaryNum;
        if(!is_null($contactPhone))$newPosition->contact_phone = $contactPhone;
        if(!is_null($contactName))$newPosition->contact_name = $contactName;
        if(!is_null($province))$newPosition->province = $province;
        if(!is_null($sex))$newPosition->sex = $sex;
        if(!is_null($city))$newPosition->city = $city;
        if(!is_null($area))$newPosition->area = $area;
        if(!is_null($town))$newPosition->town= $town;
        if(!is_null($addressDetail))$newPosition->address_detail = $addressDetail;
        if(!is_null($desc))$newPosition->desc = $desc;
        if(!is_null($education))$newPosition->education = $education;
        $newPosition->reload_time = time();
        $newPosition->state = 1;
        $newPosition->save();

        if(is_array($positionImgs) && count($positionImgs) > 0){
          $oldImgs = PositionImg::wherePositionId($newPosition->id)->get();
            if(count($oldImgs) > 0){
                foreach($oldImgs as $oldImg){
                    $oldImg->forceDelete();
                }
            }

            foreach($positionImgs as $position_imgs_id){
                $newPositionImgs = new PositionImg();
                if(!is_null($newPosition))$newPositionImgs->position_id = $newPosition->id;
                if(!is_null($position_imgs_id))$newPositionImgs->img_id = $position_imgs_id;
                $newPositionImgs->save();
            }
        }

        return response()->json(['level' => 'success','message' => '创建成功','data' => $newPosition]);
    }

    public function getPositionList(Request $request){

        $industryId  = !is_null($request->get('industry_id')) ? $request->get('industry_id'):0;
        $jobId       = !is_null($request->get('job_id')) ? $request->get('job_id'):0;
        $province    = $request->get('province');
        $city        = $request->get('city');
        $area        = $request->get('area');
        $town        = $request->get('town');
        $salaryType  = $request->get('salary_type');
        $salaryRange = $request->get('salary_range');
        $type        = $request->get('type') ? $request->get('type') : "all_list";
        $positionType= $request->get('position_type');
        $status      = $request->get('status');
        $is_top      = $request->get('is_top');
        $keyword     = $request->get('keyword');

        if(!is_null($keyword) || $keyword != ''){
            $joys = JobType::where('name','like','%'.$keyword.'%')->get();

            $joyIds = [];
            if(count($joys) > 0 ){
                foreach ($joys as $joy){
                    array_push($joyIds,$joy->id);
                }
            }

            $positions = DB::table('position')->whereNull("deleted_at")->where('desc','like','%'.$keyword.'%')->orWhere(function ($query) use($joyIds){
                $query->whereIn('job_type_id',$joyIds)->whereNull("deleted_at");
            })->get();
        }else{
            if($type != "all_list"){
                $user = UserManager::isLogin($request);
                if(!$user)
                    return response()->json(['level' => 'error','message' => '未登录无权限查看',"data"=>"no_login"]);

                if(!is_null($status) && $status != ''){
                    /** @var Position $position */
                    $positions = Position::whereUserId($user->id)->whereState($status)->orderBy('sort','asc')->orderBy("reload_time","desc")->get();
                }else{
                    /** @var Position $position */
                    $positions = Position::whereUserId($user->id)->orderBy('sort','asc')->orderBy("reload_time","desc")->get();
                }
            }else{
                $positions = DB::table("position")->whereNull("deleted_at");

                if($industryId != '' && $industryId != 0){
                    $positions->where('trade_id',"=",$industryId);
                }

                if($jobId !='' && $jobId !=0){
                    $positions = $positions->whereJobTypeId($jobId);
                }

                if(!is_null($province) && $province != ""){
                    $positions = $positions->whereCity($province);
                }

                if(!is_null($city) && $city !=""){
                    $positions = $positions->whereArea($city);
                }

                if(!is_null($area) && $area != ""){
                    $positions = $positions->whereTown($area);
                }

                if(!is_null($town) && $town != ""){
                    $positions = $positions->whereTown($town);
                }

                if(!is_null($salaryType) && $salaryType != ""){
                    $positions = $positions->whereSalaryType($salaryType);
                }


//                if(!is_null($salaryRange) && $salaryRange != ""){
//                    $arr = explode("-",$salaryRange);
//                    $positions = $positions->whereBetween('salary_num',[$arr[0],$arr[1]]);
//                }
//
//                if(!is_null($positionType) && $positionType != ""){
//                    $positions = $positions->whereType($positionType);
//                    $positions = $positions->orderBy("set_top","desc")->orderBy('sort','asc')->orderBy("reload_time","desc")->get();
//                }else{
//                    if(!is_null($is_top) && $is_top == 1){
//                        $positions = $positions->orWhere("set_top","=",1)->whereNull("deleted_at")->get();
//                    }else{
//                        $positions = $positions->orderBy("set_top","desc")->orderBy('sort','asc')->orderBy("reload_time","desc")->get();
//                    }
//                }


                if(!is_null($salaryRange) && $salaryRange != ""){
                    $arr = explode("-",$salaryRange);
                    $positions = $positions->whereBetween('salary_num',[$arr[0],$arr[1]]);
                }

                if(!is_null($positionType) && $positionType != ""){
                    $positions = $positions->whereType($positionType);
                }else{
                    if(!is_null($is_top) && $is_top == 1){
                        $positions = $positions->orWhere("set_top","=",1)->whereNull("deleted_at");
                    }
                }

                $positions = $positions->orderBy("set_top","desc")->orderBy('sort','asc')->orderBy("reload_time","desc")->get();
            }
        }

        if(count($positions) > 0){
            foreach($positions as $position){

                if($position->set_top == 1){
                    //置顶判断
                    $setTopRecord = SetTopRecord::wherePositionId($position->id)->whereStatus(1)->where("end_time",">",date("Y-m-d H:i:s",time()))->first();
                    if(!$setTopRecord){
                        DB::table('position')->where("id",$position->id)->update(["set_top"=>0]);
                    }
                }

                /** @var Position $position */
                $positionImgs = PositionImg::wherePositionId($position->id)->get();
                if(count($positionImgs) > 0){
                    foreach($positionImgs as $positionImg){
                        $positionImgUrl = FileManager::getImgFromOssUrl($positionImg->img_id);
                        $positionImg->img_url = $positionImgUrl;
                    }
                }

                switch ($position->type){
                    case 0:
                        $position->type = "长期工";
                        break;
                    case 1:
                        $position->type = "临时工";
                        break;
                    case 2:
                        $position->type = "实习";
                        break;
                }

                $jobType = JobType::whereId($position->job_type_id)->first();
                if($jobType){
                    $position->job_type = $jobType->name;
                }else{
                    $position->job_type ="无";
                }

                $userInfo = UserInfo::whereUserId($position->user_id)->first();
                if(!$userInfo){
                    $userInfo = null;
                }

                if($userInfo->realname != "" && !is_null($userInfo->realname)){
                    $userInfo->realname = mb_substr($userInfo->realname,0,1,"utf-8")."**(先生/女士)";
                }

                $announcer = 'personal';
                if($userInfo->company_auth == 1){
                    $announcer = 'company';
                    $company = array();
                    $companyInfo = CompanyInfo::whereUserId($position->user_id)->first();
                    if($companyInfo){
                        $trade = Trade::whereId($position->trade_id)->first();
                        if($trade){
                            $company['trade_name'] = $trade->name;
                        }else{
                            $company['trade_name'] = '无';
                        }
                        $companyInfo->photo_url = FileManager::getAliOssFile($companyInfo->photo_id);
                        $trade2 = Trade::whereId($companyInfo->industry_id)->first();
                        $companyInfo->industry = $trade2 ? $trade2->name : '';
                        $user = UserManager::isLogin($request);
                        $companyInfo->contact_phone = $user ? $companyInfo->contact_phone : self::hiddenPhone($companyInfo->contact_phone);
                        $company['company_info']  = $companyInfo;
                    }else{
                        $company['company_info'] = null;
                        $company['trade_name']   = '无';
                    }
                    $userInfo->photo_url = FileManager::getAliOssFile($userInfo->photo_id);
                    $company['user_info']    = $userInfo;
                    $company["user_type"] = $announcer;
                    $position->info = $company;
                }else{
                    $personal = array();
                    $personalAuth = PersonalAuth::whereUserId($position->user_id)->first();
                    $companyInfo = CompanyInfo::whereUserId($position->user_id)->first();
                    if($companyInfo){
                        $trade3 = Trade::whereId($companyInfo->industry_id)->first();
                        $companyInfo->industry = $trade3 ? $trade3->name : '';
                        $companyInfo->photo_url = FileManager::getAliOssFile($companyInfo->photo_id);

                        $user = UserManager::isLogin($request);
                        $companyInfo->contact_phone = $user ? $companyInfo->contact_phone : self::hiddenPhone($companyInfo->contact_phone);
                        $personal['company_info'] = $companyInfo;
                    }else{
                        $personal['company_info'] = null;
                    }

                    $userInfo->photo_url = FileManager::getAliOssFile($userInfo->photo_id);
                    $personal['user_info'] = $userInfo;

                    $thatTrade = Trade::whereId($position->trade_id)->first();
                    $personal['trade_name'] = $thatTrade ? $thatTrade->name : '无';

                    $personal["user_type"] = $announcer;
                    $position->info = $personal;

                }
                $position->position_img = $positionImgs;

                $user = UserManager::isLogin($request);
                if($user){
                    $hasFollow = UserFollow::whereUserId($user->id)->whereFUserId($position->user_id)->first();
                    $position->is_follow = $hasFollow ? 1 : 0;
                }else{
                    $position->is_follow = 0;
                }

                $position->salary_num = $position->salary_num != 0 ? $position->salary_num : '';
                $positionTrade = Trade::whereId($position->trade_id)->first();
                $position->trade_name = $positionTrade ? $positionTrade->name : '';

//                $position->contact_phone = $user ? $position->contact_phone : self::hiddenPhone($position->contact_phone);
            }
        }

//        var_dump($positions);die;
//        $positions = mb_convert_encoding($positions, 'UTF-8', 'UTF-8');
        return response()->json(["level"=>"success","message"=>"get_success","data"=>$positions]);
//        return response()->json(['level' => 'success','message' => '获取成功','data' => $positions]);
    }

    public function reloadPosition(Request $request){
        $id = $request->get("id");

        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录','data' => 'no_login']);

        $newPosition = Position::whereUserId($user->id)->whereId($id)->first();
        if(!$newPosition){
            return response()->json(['level' => 'error','message' => '职位不存在']);
        }

        //获取当天的最大时间和最小时间
        $ty = date('Y', time());
        $tm = date('m', time());
        $td = date('d', time());
        $todayStartTime = mktime(0,0,0,$tm,$td,$ty);
        $todayEndTime   = mktime(23,59,59,$tm,$td,$ty);

        if($newPosition->reload_time >= $todayStartTime){
            return response()->json(['level' => 'error','message' => '您今天已经刷新过了，每天只能刷新一次哦！']);
        }

        $newPosition->reload_time = time();
        $newPosition->save();

        return response()->json(['level' => 'success','message' => '刷新成功！']);
    }

    public static function hiddenPhone($str){
        $resstr=substr_replace($str,'****',3,4);
        return $resstr;     
    }

    public function getPositionDetail(Request $request){
        $id = $request->get("id");

        /** @var Position $position */
        $position = Position::whereId($id)->first();
        if(!$position)
            return response()->json(['level' => 'error','message' => '当前职位不存在']);

        /** @var Position $position */
        $positionImgs = PositionImg::wherePositionId($position->id)->get(['img_id']);

     /*   $position_img_list = array();*/
        if(count($positionImgs) > 0){
            foreach($positionImgs as $positionImg){
                /*$positionImgs->imgid=$positionImg->img_id;*/
                $positionImgUrl = FileManager::getImgFromOssUrl($positionImg->img_id);
                $positionImg->img_url = $positionImgUrl;
            }
        }

        switch ($position->type){
            case 0:
                $position->type = "长期工";
                break;
            case 1:
                $position->type = "临时工";
                break;
            case 2:
                $position->type = "实习";
                break;
        }

        $jobType = JobType::whereId($position->job_type_id)->first();
        if($jobType){
            $position->job_type = $jobType->name;
        }else{
            $position->job_type ="无";
        }

        $userInfo = UserInfo::whereUserId($position->user_id)->first();
        if(!$userInfo)
            return response()->json(['level' => 'error','message' => '用户信息不完整']);

        if($userInfo->realname != "" && !is_null($userInfo->realname)){
            $userInfo->realname = mb_substr($userInfo->realname,0,1,"utf-8")."**(先生/女士)";
        }

        $announcer = 'personal';
        if($userInfo && $userInfo->company_auth == 1){
            $announcer = 'company';
            $company = array();
            $companyInfo = CompanyInfo::whereUserId($position->user_id)->first();
            if($companyInfo){
                if($companyInfo->contacts != "" && !is_null($companyInfo->contacts)){
                    $companyInfo->contacts = mb_substr($companyInfo->contacts,0,1,"utf-8")."**(先生/女士)";
                }

                $trade = Trade::whereId($position->trade_id)->first();
                if($trade){
                    $company['trade_name'] = $trade->name;
                }else{
                    $company['trade_name'] = '无';
                }

                $user = UserManager::isLogin($request);
                $companyInfo->contact_phone = $user ? $companyInfo->contact_phone : self::hiddenPhone($companyInfo->contact_phone);

                $trade2 = Trade::whereId($companyInfo->industry_id)->first();
                $companyInfo->industry = $trade2 ? $trade2->name : 0 ;

                $companyInfo->img_url = FileManager::getAliOssFile($companyInfo->photo_id);
                $company['company_info']  = $companyInfo;

                $userInfo->img_url = FileManager::getAliOssFile($userInfo->photo_id);
                $company['user_info']     = $userInfo;
            }else{
                $company['company_info'] = null;
                $company['user_info']    = $userInfo;
                $company['trade_name']   = null;
            }

            $company["user_type"] = $announcer;
            $position->info = $company;
        }else{

            $personal = array();

            $companyInfo = CompanyInfo::whereUserId($position->user_id)->first();

            if($companyInfo){
                if($companyInfo->contacts != "" && !is_null($companyInfo->contacts)){
                    $companyInfo->contacts = mb_substr($companyInfo->contacts,0,1,"utf-8")."**(先生/女士)";
                }

                $trade3 = Trade::whereId($companyInfo->industry_id)->first();
                $companyInfo->industry = $trade3 ? $trade3->name : 0 ;

                $companyInfo->img_url = FileManager::getAliOssFile($companyInfo->photo_id);
                $personal['company_info'] = $companyInfo;
            }else{
                $personal['company_info'] = null;
            }

            $userInfo->img_url = FileManager::getAliOssFile($userInfo->photo_id);
            $personal['user_info'] = $userInfo;

            $thatTrade = Trade::whereId($position->trade_id)->first();
            $personal['trade_name'] = $thatTrade ? $thatTrade->name : '无';

            $personal["user_type"] = $announcer;
            $position->info = $personal;
        }
 /*       $position->position_img = $position_img_list;*/
        $position->position_img = $positionImgs;

        $position->salary_num = $position->salary_num != 0 ? $position->salary_num : '';

        $positionTrade = Trade::whereId($position->trade_id)->first();
        $position->trade_name = $positionTrade ? $positionTrade->name : '';

        $user = UserManager::isLogin($request);
        $position->contact_phone = $user ? $position->contact_phone : self::hiddenPhone($position->contact_phone);

        $user = UserManager::isLogin($request);
        if($user){
            $hasFollow = UserFollow::whereUserId($user->id)->whereFUserId($position->user_id)->first();
            $position->is_follow = $hasFollow ? 1 : 0;
        }else{
            $position->is_follow = 0;
        }
        return response()->json(['level' => 'success','message' => '获取成功','data' => $position]);
    }

    public function setTopRule(Request $request){
       $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请登录',"data"=>"no_login"]);
        $thatSetTopRule=SetTopRule::orderBy('created_at','desc')->get();
        return response()->json(['level' => 'success','message' => '获取成功','data' => $thatSetTopRule]);
    }

}
